Strobogrammatic Number III

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high.

For example,
Given low = “50”, high = “100”, return 3. Because 69, 88, and 96 are three strobogrammatic numbers.

Note:

Because the range might be a large number, the low and high numbers are represented as string.

Solution:

  1. public class Solution {
  2. int count = 0;
  3. String[][] pairs = {{"0", "0"}, {"1", "1"}, {"6", "9"}, {"8", "8"}, {"9", "6"}};
  4. public int strobogrammaticInRange(String low, String high) {
  5. Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
  6. map.put(0, new ArrayList<String>(Arrays.asList("")));
  7. map.put(1, new ArrayList<String>(Arrays.asList("0", "1", "8")));
  8. for (int i = low.length(); i <= high.length(); i++)
  9. helper(i, map, low, high);
  10. return count;
  11. }
  12. List<String> helper(int n, Map<Integer, List<String>> map, String low, String high) {
  13. List<String> res = new ArrayList<String>();
  14. if (map.containsKey(n)) {
  15. res = map.get(n);
  16. } else {
  17. List<String> list = map.containsKey(n - 2) ? map.get(n - 2) : helper(n - 2, map, low, high);
  18. for (int i = 0; i < list.size(); i++) {
  19. String s = list.get(i);
  20. for (int j = 0; j < pairs.length; j++) {
  21. String v = pairs[j][0] + s + pairs[j][1];
  22. if (v.length() == high.length() && v.compareTo(high) > 0)
  23. break;
  24. res.add(v);
  25. }
  26. }
  27. map.put(n, res);
  28. }
  29. if (n >= low.length()) {
  30. count += res.size();
  31. for (String s : res) {
  32. if ((s.length() > 1 && s.charAt(0) == '0') || (s.length() == low.length() && s.compareTo(low) < 0) || (s.length() == high.length() && s.compareTo(high) > 0))
  33. count--;
  34. }
  35. }
  36. return res;
  37. }
  38. }